/**
 * 2017年7月11日
 */
package org.textplantform.common.core;

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.Collectors;

import org.textplantform.common.api.AfterInitializationExecute;

import com.mongodb.Mongo;
import com.mongodb.ServerAddress;

/**
 * @author Alex
 *
 */
public class MongoDBClient extends LoggerSupport implements AfterInitializationExecute{
	protected Mongo m;
	protected String str;
	public MongoDBClient(String connectionStr) {
		this.str = connectionStr;
	}
	@Override
	public void executeAfterBeanInitialization() {
		try {
			if(str.indexOf(',')!=-1){
				m = new Mongo( Arrays.asList(str.split(",")).stream().map(x->{
					String []infos = x.split(":");
					try {
						return new ServerAddress(infos[0],Integer.parseInt(infos[1]));
					} catch (Exception e) {
						logException(e);
						return null;
					}
				}).collect(Collectors.toList()));
			}else{
				m = new Mongo(str);
			}
		
		} catch (UnknownHostException e) {
			logException(e);
		}
	}
	public Mongo getMongo(){
		return m;
	}
	
	
}
